<template>
  <div id="box">
    <div class="content-wrapper">
      <div class="search-bar">
        <div class="search-bar-inner">
          <el-form :inline="true" :model="param" class="demo-form-inline" size="small">

            <el-form-item label="账号">
              <el-input v-model="param.username"/>
            </el-form-item>

            <el-form-item label="昵称">
              <el-input v-model="param.nickName"/>
            </el-form-item>

            <el-form-item label="状态">
              <el-select clearable v-model="param.state" :placeholder="null">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSearch(1)" icon="el-icon-search">查询</el-button>
              <el-button @click="resetForm('formName')">重置</el-button>
              <el-button type="success" @click="openAddDialog" plain icon="el-icon-folder-add">新增</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div class="dataTable" ref="tableWrapper">
        <el-table :data="tableData" v-loading="loading" border size="small"
                  :header-cell-style="{background:'#f5f7fa',color:'#909399', padding:'8px 0', 'text-align':'center'}"
                  class="el-table"
                  :height="tableHeight"
        >
          <el-table-column type="index" label="序号" align="center" width="60"/>
          <el-table-column prop="username" label="账号" show-overflow-tooltip align="center"/>
          <el-table-column prop="nickName" label="昵称" show-overflow-tooltip align="center"/>
          <el-table-column prop="num" label="电话号码" show-overflow-tooltip align="center"/>
          <el-table-column prop="email" label="邮箱" show-overflow-tooltip align="center"/>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-tag
                  :type="scope.row.state === 1 ? 'success' : 'danger'"
                  disable-transitions
                  size="mini"
              >
                {{ scope.row.state === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200px">
            <template slot-scope="scope">
              <el-button type="primary"
                         size="mini"
                         icon="el-icon-edit"
                         @click="handleEdit(scope.row)"
              >编辑
              </el-button>

              <el-button type="danger" size="mini"
                         @click="handleDelete(scope.row.id)"
                         icon="el-icon-delete">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pager :total="total" :page-size="param.pageSize" :page-num="param.pageNum"
               @page-change="handlePageChange"/>
      </div>

      <!-- 新增对话框 -->
      <el-dialog center title="新增用户" :visible.sync="dialogVisible" width="610px" :before-close="closeAddDialog">
        <el-form :model="formAdd" label-width="80px" :rules="rules" ref="formAdd">

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账号" prop="username">
                <el-input v-model="formAdd.username" size="small" placeholder="请输入账号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input v-model="formAdd.password" size="small" placeholder="请输入密码"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="昵称" prop="nickName">
                <el-input v-model="formAdd.nickName" size="small" placeholder="请输入昵称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话" prop="num">
                <el-input v-model="formAdd.num" size="small" placeholder="请输入电话号码"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formAdd.email" size="small" placeholder="请输入邮箱"/>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">取消</el-button>
          <el-button size="small" type="primary" @click="submitAdd">确定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑对话框 -->
      <el-dialog center title="编辑用户" :visible.sync="dialogVisibleEdit" width="610px"
                 :before-close="closeEditDialog">
        <el-form :model="formEdit" label-width="80px">

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账号">
                <el-input v-model="formEdit.username" disabled size="small"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码">
                <el-input v-model="formEdit.password" size="small"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="昵称">
                <el-input v-model="formEdit.nickName" size="small"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话">
                <el-input v-model="formEdit.num" size="small"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱">
                <el-input v-model="formEdit.email" size="small"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-select clearable v-model="formEdit.state" size="small">
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="禁用" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogVisibleEdit = false">取消</el-button>
          <el-button size="small" type="primary" @click="submitEdit">确定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
// import axios from 'axios';
import request from '@/utils/request';
import pager from '@/components/pager.vue';

export default {
  components: {
    pager
  },
  name: 'UserManagement',
  data() {
    return {
      tableData: [],
      param: {
        username: '',  //账号
        state: null,  //状态
        nickName: '',  //昵称
        pageNum: 1,
        pageSize: 10,
      },

      total: 0,

      loading: false,

      tableHeight: 50,

      dialogVisible: false,  // 控制新增弹窗
      dialogVisibleEdit: false,  //控制编辑弹窗

      formAdd: {
        username: '',
        password: '',
        nickName: '',
        num: null,
        email: '',
        state: null
      },

      rules: {
        username: [
          {required: true, message: '账号不能为空', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: '昵称不能为空', trigger: 'blur'}
        ],
        num: [
          {required: true, message: '电话号码不能为空', trigger: 'blur'},
          {type: 'number', message: '请输入有效的手机号码'}
        ],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur'}
        ]
      },

      formEdit: {
        username: '',
        password: '',
        nickName: '',
        num: null,
        email: '',
        state: null
      },

    };
  },
  computed: {},
  mounted() {
    this.handleSearch();
  },

  methods: {

    // 分页器页码变化时触发
    handlePageChange(newPage) {
      this.param.pageNum = newPage; // 更新 param 中的页码
      // console.log(newPage)
      this.handleSearch(newPage);   // 重新查询
    },

    // 查询
    handleSearch(page = this.param.pageNum) {

      this.param.pageNum = page;
      this.loading = true;
      request.get('/api/users', {
        params: this.param,
      })
          .then(data => {
            // setTimeout(() => {
            this.tableData = data.content;
            this.total = data.total;
            this.loading = false;
            // }, 500);
          })
          .catch(error => {
            console.error('失败:', error);
            this.$message.error(error.message || '失败');
            this.loading = false;
          })
    },

    // 打开新增弹框
    openAddDialog() {
      this.formAdd = {
        username: '',
        password: '',
        nickName: '',
        num: null,
        email: '',
        state: null
      };
      this.dialogVisible = true;
    },

    // 提交新增
    submitAdd() {
      this.$refs.formAdd.validate((valid) => {
        if (valid) {
          request.post('/api/users', this.formAdd)
              .then(data => {
                this.$message.success(data.message);
                this.dialogVisible = false;
                this.handleSearch();
              })
              .catch(error => {
                this.$message.error(error.message || '新增失败');
                console.error(error);
              });
        } else {
          return false
        }
      });
    },

    closeAddDialog() {
      this.dialogVisible = false;
    },

    // 编辑
    handleEdit(row) {
      this.dialogVisibleEdit = true;
      this.formEdit = {
        id: row.id,
        username: row.username,
        password: row.password,
        nickName: row.nickName,
        num: row.num,
        email: row.email,
        state: row.state,
        page: row.page,
      }
    },

    // 编辑提交
    submitEdit() {
      request.post('/api/editUsers', this.formEdit)
          .then(data => {
            console.log(data)
            this.$message.success(data.message);
            this.dialogVisibleEdit = false;
            this.handleSearch();
          })
          .catch(error => {
            this.$message.error(error.message || '新增失败');
            console.error(error);
          });
    },

    // 关闭编辑对话框
    closeEditDialog() {
      this.dialogVisibleEdit = false;
    },

    //重置
    resetForm() {
      this.param = {
        username: '',
        state: null,
        nickName: ''
      };
      this.pageNum = 1;
      this.handleSearch();
    },

    // 删除用户
    handleDelete(id) {
      this.$confirm('此操作将永久删除该用户，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.post('/api/deleteUser', {id})
            .then(data => {
              this.$message.success(data.message || '删除成功');
              this.handleSearch();
            })
            .catch(error => {
              this.$message.error(error.message || '删除失败');
              console.error(error);
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

  }
};
  
</script>

<style scoped>
#box {
  width: 100%;
  min-width: 1024px;
  height: calc(100vh - 40px);
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background-color: #f5f7fa;
}

.content-wrapper {
  width: 95%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.search-bar {
  margin-top: 10px;
  width: 100%;
  padding: 0 10px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
  border-radius: 8px;
}

.search-bar-inner {
  margin-top: 20px;
}

.dataTable {
  width: 100%;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 20px;
  height: calc(100vh - 180px);
  overflow: hidden;

  display: flex;
  flex-direction: column;
}

.dataTable .el-table {
  flex: 95%;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

</style>
